package cn.group7.padserver.handler.authentication;

import cn.group7.padserver.common.Flag;
import cn.group7.padserver.controller.responseformat.Code;
import cn.group7.padserver.controller.responseformat.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 谷汉斌
 * @description （请求路径有误，或未登录，或服务器出错）
 * @createTime 2024/7/24 上午9:56
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        Result result = Result.builder()
                .flag(Flag.FAIL.isCode())
                .code(Code.ERROR.getCode())
                .message("发生错误：原因可能是请求路径有误，未登录，无权限或服务器升级中！").build();
        String s = JSON.toJSONString(result);
        outputStream.write(s.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}